package org.itboys.core.common;

import org.apache.shiro.authz.UnauthorizedException;
import org.itboys.commons.ErrorException;
import org.itboys.core.util.ResponseMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

/**
 * 作者：zzq
 * 时间：2018/8/24
 * 描述：统一接口捕获异常
 */
@ControllerAdvice
public class ExceptionHandle {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    @ExceptionHandler(value = Exception.class)
    public void handle(Exception e,HttpServletRequest request){
        logger.error("请求路径#################################"+request.getRequestURL().toString());
        logger.error(getExceptionPoint(e));
        e.printStackTrace();
        String message=e.getMessage();
        if (e instanceof ErrorException) {
            //自定义异常
            ResponseMessage.error(ExceptionEnum.getExceptionEnum(message).getCode(),message);
        }else if(e instanceof UnauthorizedException){
            //权限异常
            ResponseMessage.error(ExceptionEnum.AUTHEXCPTION.getCode(),ExceptionEnum.AUTHEXCPTION.getValue());
        }else if(e instanceof Exception){
            //系统异常
            ResponseMessage.error(ExceptionEnum.EXCPTION.getCode(),message);
        }
    }
    public static String getExceptionPoint(Exception ex) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PrintStream pout = new PrintStream(out);
        ex.printStackTrace(pout);
        String ret = new String(out.toByteArray());
        pout.close();
        try {
            out.close();
        } catch (Exception e) {
        }
        ret=ret.substring(0,ret.indexOf(")")+1);
        return ret;
    }
}
